package edu.fim.presentation.controller;

import edu.fim.core.exception.BmiOutOfRangeException;
import edu.fim.core.exception.ServiceException;
import edu.fim.core.service.ConsumerService;
import edu.fim.core.service.locator.BeanLocator;
import edu.fim.core.service.locator.ServiceLocator;
import edu.fim.core.util.BmiCategories;
import edu.fim.presentation.controller.exception.ControllerException;
import edu.fim.presentation.model.bean.Consumer;
import edu.fim.presentation.model.bean.Food;

public class ConsumerController {

	private Consumer currentConsumer;

	public ConsumerController(Consumer currentConsumer) {
		this.currentConsumer = currentConsumer;
	}

	public Consumer getCurrentConsumer() {
		return currentConsumer;
	}

	public void setCurrentConsumer(Consumer currentConsumer) {
		this.currentConsumer = currentConsumer;
	}
	
	public void setCaloriesThreshold(Double newThreshold) throws ControllerException {
		ConsumerService consumerService = BeanLocator.getInstance().getServiceBean(ConsumerService.class);
		try {
			consumerService.setCaloriesThreshold(currentConsumer, newThreshold);
			currentConsumer.setCaloriesThreshold(newThreshold);
		}
		catch (ServiceException e) {
			e.printStackTrace();
			throw new ControllerException(e.getMessage());
		}
	}
	
	public void updatePreferences() {
		ConsumerService consumerService = ServiceLocator.getImplementation(ConsumerService.class);
		consumerService.updatePreferences(currentConsumer);
	}

	public void registerIngestion(Food food) throws ControllerException {
		ConsumerService cs = ServiceLocator.getImplementation(ConsumerService.class);
		try {
			cs.increaseCalories(currentConsumer, food);
		}
		catch (ServiceException e) {
			e.printStackTrace();
			throw new ControllerException(e.getMessage());
		}
	}

	public BmiCategories determineBmi() throws ControllerException {
		ConsumerService cs = ServiceLocator.getImplementation(ConsumerService.class);
		try {
			return cs.determineWeightSituation(currentConsumer);
		}
		catch (BmiOutOfRangeException e) {
			e.printStackTrace();
			throw new ControllerException("The BMI calculated is out of range.");
		}
	}
	
	public void resetCalories() throws ControllerException {
		currentConsumer.setConsumedCalories(0.0);
		ConsumerService service = ServiceLocator.getImplementation(ConsumerService.class);
		try {
			service.update(currentConsumer);
		} catch (ServiceException e) {
			throw new ControllerException("Error during update.", e);
		}
	}
}